#include "friendlistform.h"

#include "ui_friendlistform.h"

#include <Application.h>
#include <CommonUtils.h>
#include <forms/mainwindow/listforms/chatlistform.h>

FriendListForm::FriendListForm(WindowManager& manager, QWidget* parent) : QWidget(parent),
                                                                          manager(manager),
                                                                          ui(new Ui::FriendListForm) {
    ui->setupUi(this);
    CommonUtils::loadStyleSheet(this, "scrollBar");
    init();
    ui->listWidget->setVerticalScrollBarPolicy(Qt::ScrollBarPolicy::ScrollBarAlwaysOff);
    ui->listWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarPolicy::ScrollBarAlwaysOff);
}

FriendListForm::~FriendListForm() {
    delete ui;
}

void FriendListForm::init() {
    auto app = Application::instance();
    connect(app, &Application::signalGetFriendList, this, &FriendListForm::onGetFriendsList);
    connect(app, &Application::signalAddFriends, this, &FriendListForm::onAddFriends);
    connect(ui->listWidget, &QListWidget::itemClicked, this, &FriendListForm::onItemClicked);
    connect(ui->listWidget, &QListWidget::itemDoubleClicked, this, &FriendListForm::onItemDoubleClicked);
}

void FriendListForm::initFriendsList() {
    for (auto&& i : m_firends) {
        // manager.addSubWindow
        addWidget(*i.second);
    }
}

void FriendListForm::addWidget(data::FriendInfo& info) {
    QListWidgetItem* item     = new QListWidgetItem(ui->listWidget);
    UserItem*        userItem = new UserItem(ui->listWidget);

    ui->listWidget->addItem(item);
    ui->listWidget->setItemWidget(item, userItem);
    item->setSizeHint(QSize(172, 74));

    userItem->setUserId(info.userid().c_str());
    userItem->setSign(info.sign().c_str());
    userItem->setName(info.name().c_str());
    userItem->setPixmap(info.headshot().c_str());
}

void FriendListForm::onGetFriendsList(int code) {
    if (!code) {
        for (auto&& i : Application::instance()->firends()) {
            m_firends[QString::fromStdString(i->userid())] = i;
        }

        initFriendsList();
    }
}

void FriendListForm::onAddFriends(int code, QString message, std::shared_ptr<::proto::data::FriendInfo> info) {
    if (!code) {
        m_firends[QString::fromStdString(info->userid())] = info;
        addWidget(*info);
    }
}

void FriendListForm::onItemClicked(QListWidgetItem* item) {
}

void FriendListForm::onItemDoubleClicked(QListWidgetItem* item) {
    QWidget*  widget   = ui->listWidget->itemWidget(item);
    UserItem* userItem = static_cast<UserItem*>(widget);

    auto userId = userItem->getUserId();

    qDebug() << "userId :" << userId;
    auto f = m_firends[userId];
    qDebug() << "userId :" << f->userid().c_str();

    auto* chatListForm = manager.getChatListForm();
    if (chatListForm) {
        chatListForm->addNewChat(*f);
    }

    emit signalToggle();
}

